//
//  LoadingView.swift
//  demo
//
//  Created by Xiaoping Tang on 2023/3/17.
//

import Foundation
import UIKit
import SwiftUI

extension UIViewController {
    static func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController {
        
        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }
        
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }
        
        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }
        
        return base!
    }
}

class LoadingView {
    static var window: UIWindow?
    
    public static func show() {
        let rootView = AnyView(
            ZStack {
                Color.black
                    .opacity(0.85)
                    .edgesIgnoringSafeArea(.all)
                Text("Loading").foregroundColor(.white)
            }
        )
        let vc = UIHostingController(rootView: rootView)

//        let rootView = UIView()
//        let vc = UIViewController()
//        vc.view = rootView;
        
        vc.modalPresentationStyle = .fullScreen
        if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
            window = UIWindow(windowScene: scene)
        } else {
            window = UIWindow(frame: UIScreen.main.bounds)
        }
        window?.backgroundColor = .clear
        window?.windowLevel = .alert
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
//        window?.rootViewController?.present(vc, animated: false)
//        vc.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
//        let root = UIViewController.topViewController()
//        root.present(vc, animated: false)
    }
    
    public static func hide() {
        window?.rootViewController = nil
        window = nil
//        let root = UIViewController.topViewController()
//        root.dismiss(animated: false)
    }
}
